<template>
  <div class="app-container">
    <el-collapse v-model="activeNames">
      <el-collapse-item name="1">
        <template #title>
            <div style="font-size: 15px;font-weight: 400;color: #333;"><span>条件查询</span></div>
        </template>
        <template #icon="{ isActive }">
          <div class="icon-ele">{{ isActive ? '展开' : '折叠' }}</div>
        </template>
        <div class="top-main">
            <el-row>
              <el-col :span="22">
                <el-form :model="param" :inline="true" label-width="100px">
                  <el-form-item label="箱号">
                    <MultipleBoxNumbersDialog v-model.trim="param.containerNo"/>
                  </el-form-item>
                  <el-form-item label="订单号">
                    <el-input v-model.trim="param.orderNo" placeholder="请输入订单号"> </el-input>
                  </el-form-item>
                  <el-form-item label="业务编号">
                    <el-input v-model.trim="param.businessNo" placeholder="请输入"> </el-input>
                  </el-form-item>
                  <el-form-item label="提箱城市">
                    <city-select :selectCity="param.boxStartCity" @cityId="startCityId" style="width: 100%;"></city-select>
                  </el-form-item>
                  <el-form-item label="还箱城市">
                    <city-select :selectCity="param.boxBackCity" @cityId="backCityId" style="width: 100%;"></city-select>
                  </el-form-item>
                  <el-form-item label="下单日期">
                    <el-date-picker v-model="param.createDate" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
                  </el-form-item>
                  <el-form-item label="预计提箱日期">
                    <el-date-picker v-model="param.planPickupDate" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" />
                  </el-form-item>
                  <el-form-item label="集装箱公司">
                    <el-input v-model.trim="param.companyName" placeholder="请输入"> </el-input>
                  </el-form-item>
                  <el-form-item label="发票状态">
                    <el-select v-model="param.invoiceStatus" placeholder="请选择">
                      <el-option v-for="item in param.invoiceStatusList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="支付状态">
                    <el-select v-model="param.payStatus" placeholder="请选择">
                      <el-option label="未付" value="5"></el-option>
                      <el-option label="已付" value="15"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="操作员">
                    <el-input v-model.trim="param.agentOperatorUserName" placeholder="请输入"> </el-input>
                  </el-form-item>
                </el-form>
              </el-col>
              <el-col :span="2">
                <el-row>
                    <el-col :span="24" class="text-center">
                      <el-button @click="handleReSet" :icon="Refresh">重置</el-button>
                    </el-col>
                    <el-col :span="24" class="text-center marginTop17">
                      <el-button @click="getTableData" :icon="Search" type="primary">查询</el-button>
                    </el-col>
                </el-row>
              </el-col>
            </el-row>
        </div>
      </el-collapse-item>
    </el-collapse>
  
    <cz-tages :bottomLine="true" :typeList="typeList" @handleTypeChange="handleTypeChange" style="float: left;"></cz-tages>
    <span style="margin-top: -30px;float: right;">
      <el-dropdown placement="top" :hide-on-click="false" class="floatLeft" style="margin-right: 12px;">
        <el-button :icon="Grid" type="primary" size="small">自定义显示列</el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item>
              <div class="mt-2" style="min-width: 600px;">
                <el-checkbox-group v-model="showTableItem" @change="handleGroupChange" :min="5">
                  <el-row style="width: 100%;">
                      <el-col :span="4" v-for="(item,index) in table.header"  :key="index">
                        <el-checkbox  :label="item.title" :value="item.key" size="small" />
                      </el-col>
                  </el-row>
                </el-checkbox-group>
              </div>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <el-tooltip effect="dark" content="此按钮可选择当前页及后续页所有订单" placement="left">
        <template v-if="isSelectAll">
          <el-button :icon="Finished" size="small" @click="slectAll" plain class="floatLeft">全选</el-button>
        </template>
        <template v-else>
            <el-button size="small" @click="deselectAll" plain class="floatLeft">取消全选</el-button>
        </template>
      </el-tooltip>
      <el-button type="primary" size="small" style="width:55px" @click="handleExport" plain class="floatLeft">导出</el-button>
      <!-- <el-button type="primary" size="small" style="width:65px" @click="handleApplyRefund" plain round>申请退款</el-button>
      <el-button type="primary" size="small" style="width:65px" @click="handleApplyInvoiceOpen" plain round>申请发票</el-button> -->
      <el-button v-if="param.isShowTW" type="primary" size="small" style="width:55px"  class="floatLeft" @click="handlePickupBox " plain round>提完</el-button>
      <el-button type="primary" size="small" style="width:65px" class="floatLeft" @click="batchDelete" plain round>删除</el-button>
    </span>
    <Table ref="tableRef" v-bind="table" :allId="allId" :isAllCheck="isAllCheck" @pageChange="onTablePageChange" @showInfo="showInfo" @deleteItem="deleteItem" @endPacking="endPacking"
      @handlePayOpen="handlePayOpen" @handleShowContract="handleShowContract" @updateSelectAll="updateSelectAll" :disableHeaderCheckbox="disableHeaderCheckbox">
    </Table>

    <!-- 支付租箱费 -->
    <el-dialog v-model="param.dialogVisible" style="width:500px;box-sizing:bolder;padding:40px ">
      <span style="font-weight: 700;font-size: 15px;">
        <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>支付租箱费
      </span>
      <table style="font-size: 14px;width: 400px;margin-top: 30px;">
        <tbody>
        <tr style="width: 100px;">
          <td>箱型</td>
          <td>{{ boxTypeFilter(rowData.boxType) }}</td>
        </tr>
        <tr>
          <td>应提箱量</td>
          <td>{{ rowData.totalQuantity || rowData.boxQuantity }}</td>
        </tr>
        <tr>
          <td>实提箱量</td>
          <td>{{ rowData.packedQuantity }}</td>
        </tr>
        <tr>
          <td>应付租箱费</td>
          <td>￥ {{ rowData.amount }}</td>
        </tr>
        <tr>
          <td>实付租箱费</td>
          <td>￥ {{ rowData.actualPayAmount }}</td>
        </tr>
        <tr>
          <td>优惠券</td>
          <td>{{ rowData.couponAmount }}</td>
        </tr>
        </tbody>
      </table>
      <el-form style="margin-top: 20px">
        <el-form-item>
          <div>支付方式</div>
          <el-select v-model="rowData.paymentMethod" style="width:100%;min-width: 200px;" placeholder="选择">
            <el-option v-for="item in param.paymentMethodList" :key="item.value" :label="item.label"
              :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <div>电子回执单</div>
          <input type="file" style="width:100%" />
        </el-form-item>
        <el-form-item>
          <div>支付时间</div>
          <el-date-picker v-model="rowData.payDate" type="date" style="width:100%" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handlePay" style="margin-top: 40px;text-align: right;">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 申请发票 -->
    <el-drawer v-model="param.drawer" :with-header="false" size="40%">
      <applyInvoice :tableData="param.tableData" :statusType="param.statusType"
        @requestInvoiceSuccess="requestInvoiceSuccess">
      </applyInvoice>
    </el-drawer>
    <!-- 申请退款 -->
    <el-dialog v-model="param.dialogVisibleRefund" width="60%">
      <refundCard :selection="tableRef.multipleSelection" :pageName="'rent'" :opr="'apply'" @close="handleClose">
      </refundCard>
    </el-dialog>

    <!-- 订单申请协议 -->
    <el-dialog v-model="param.dialogContract" :with-header="false">
      <pdfViewer :url="param.contractUrl"></pdfViewer>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import pdfViewer from '@/components/pdf'
import refundCard from '@/views/components/order/refundCard'
import Table from '@/components/table'
import czTages from '@/components/chengzhiTags'
import applyInvoice from '@/views/components/order/applyInvoice.vue'
import { getTable, exportAgentRentOrder,carryFinish,agentStatusCount ,rentOrders} from '@/api/orderManage/index'
import citySelect from '@/components/citySelect'
import orderInfo from '@/store/modules/order'
import { finishPacking, downloadPacking, orderBoxQty } from '@/api/orderManage/packing'
import { payBoxLabelInvoice } from '@/api/invoice'
import { computed, onActivated, onMounted, reactive, ref } from 'vue';
import { Finished, Document,Refresh ,Search,Grid} from '@element-plus/icons-vue'
import { useRouter ,useRoute} from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus'
import { downloadFile } from '@/utils/download'
import MultipleBoxNumbersDialog from '@/components/dialog/multipleBoxNumbersDialog'
import {formatContainerNo} from '@/utils/mlpBox' // 格式化箱号
const router = useRouter();

const activeNames = ref(['0'])
const showTableItem = ref<string[]>([])
  const handleGroupChange = () => {
  sessionStorage.setItem(String(route.name), JSON.stringify(showTableItem.value));
  table.header.forEach(item => {
    item.isCheck = showTableItem.value.includes(item.key)
  })
}

onMounted(()=>{
  const showTableItemStr = sessionStorage.getItem(String(route.name))
  if(sessionStorage.getItem(String(route.name))?.length && showTableItemStr){
    showTableItem.value =  JSON.parse(showTableItemStr)
  }else{
    table.header.forEach(item=>{
      showTableItem.value.push(item.key)
    })
  }
  handleGroupChange()
})
const param = reactive({
  loading: false,
  pageNum: 1,
  pageSize: 10,// 订单状态 5- 待开提箱单 10-待提未付|待提未收 15-已提未付|已提未收 20-待还未付|待还未收 25-待还已付|待还已收 30-已完成 35-已取消
  stateFilter: { //2-待确认 3-待审核 5-已下单|待开提箱单 10-待提 15-已提 20-待还 25-已还 30-已完成 35-已取消 40-待取消
    2: '待确认',
    3: '待审核',
    5: '待开提箱单',
    10: '待提未付',
    15: '已提未付',
    20: '未还',
    25: '待还已付',
    28: '已还未付',
    30: '已完成',
    40: '待取消',
    35: '已取消',

  },
  invoiceStatusList: [ //invoiceStatus; 发票状态 5-未申请 10-待开票 15-已开票
    { value: '5', label: '未申请' },
    { value: '10', label: '待开票' },
    { value: '15', label: '已开票' },
  ],
  // stateColor: { 5: '#22A86D', 10: '#2158F3', 15: '#2158F3' },
  boxTypeOptions: [ // 5 - 40HQ   10 - 40GP  15 - 20HQ   20 - 20GP
    { value: '5', label: '40HQ', },
    { value: '10', label: '40GP', },
    { value: '15', label: '20HQ', },
    { value: '20', label: '20GP', },
  ],
  boxCaseOptions: [ //5-全新   10-次新  15-适货 20-混提(次新或者适货)
    { value: '15', label: '适货', },
    { value: '10', label: '次新', },
    { value: '20', label: '混提(次新或者适货)', },
    { value: '5', label: '全新', },
  ],
  paymentMethodList: [{ value: 5, label: '对公转账' }, { value: 10, label: '在线支付' }],
  beginTotalRentQty: '',
  endTotalRentQty: '',
  boxBackCity: '',
  boxStartCity: '',
  startCityOptions: [],
  backCityOptions: [],
  refundStatusFilter: { '5': '待退款', '10': '已退款', '15': '拒绝退款'}, //5-待退款 10-已退款 15-拒绝退款
  isShowTW: false, // 控制提完按钮是否显示
  statusType:'',
  status:'',
  payStatus: ''
});

const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    // { key: 'orderNo', key2: 'orderTypeAndRefundStatus', colWidth: '200', title: '订单号', type: '<a>', command: 'showInfo', isCheck: true },
    { key: 'orderNo', colWidth: '200', title: '订单号', type: '<a>', command: 'showInfo', fixed:'left', isCheck: true },
    { key: 'businessNo', colWidth: '100', title: '业务编号', type: 'text', fixed:'left',isCheck: true },
    { key: 'carryCityName', key2: 'carryCountryName', colWidth: '100', title: '提箱城市', type: 'text',fixed:'left',  isCheck: true },
    { key: 'returnCity', colWidth: '160', title: '还箱城市', type: 'moreCity',fixed:'left',  isCheck: true },
    { key: 'createTime', colWidth: '200', title: '下单日期', type: 'dateTime', isCheck: true },
    { key: 'planPickupDate', colWidth: '150', title: '预计提箱日期', type: 'date', isCheck: true },
    { key: 'boxType', colWidth: '120', title: '箱型', type: 'filter', filter: { 5: '40HQ', 10: '40GP', 15: '20HQ', 20: '20GP' }, isCheck: true },
    { key: 'boxCondition', colWidth: '120', title: '箱况', type: 'filter', filter: { 5: '全新', 10: '次新', 15: '适货' ,20: '混提'}, isCheck: true },
    { key: 'boxUsagePeriod', colWidth: '120', title: '箱使期', type: 'add', after: '天', isCheck: true },
    { key: 'boxQuantity', colWidth: '100', title: '箱量', type: 'text', isCheck: true },
    { key: 'packedQuantity', colWidth: '100', title: '已提箱量', type: 'text', isCheck: true },
    { key: 'returnedQuantity', colWidth: '100', title: '已还箱量', type: 'text', isCheck: true },
    { key: 'amountCny',key2:'amountUsd', colWidth: '120', title: '订单金额', type: 'amount', before: '￥',currency:"currency", isCheck: true },
    { key: 'status', colWidth: '120', title: '订单状态', type: 'filter',roleType:'hd', filter: param.stateFilter, isCheck: true },
    // { key: 'invoiceNo', colWidth: '120', title: '发票号', type: 'text', isCheck: true },
    // { key: 'invoiceStatus', colWidth: '100', title: '发票状态', type: 'filter', filter: { 5: '未申请', 10: '待开票', 15: '已开票' ,20: '待红冲',25: '已红冲'}, isCheck: true },
    { key: 'boxEastUserName', colWidth: '100', title: '联系人', type: 'text', isCheck: true },
    { key: 'agentOperatorUserName', colWidth: '100', title: '操作员', type: 'text', isCheck: true },
    // { key: 'boxEastUserName', colWidth: '120', title: '联系人电话', type: 'text', isCheck: true },
    // { key: 'boxEastUserTel',key2: 'boxEastUserAreaCode', colWidth: '150', title: '联系电话', type: 'mobileCode',isCheck: true },

    // { key: 'boxQuantity', colWidth: '120', title: '订单申请', type: 'text', isCheck: true },
    // {
    //   key: 'operate',
    //   colWidth: '200',
    //   title: '订单申请协议',
    //   type: 'operate',
    //   isCheck: true,
    //   buttons: [
    //     {
    //       icon: Document,
    //       command: 'handleShowContract',
    //       isShow: (row) => {
    //         return row.downloadUrl
    //       },
    //     },
    //   ],
    // },
    { key: 'companyName', colWidth: '250', title: '集装箱公司', type: 'text', isCheck: true },
    // { key: '查看发票', colWidth: '120', title: '发票', type: '<a>', command: 'showInfo', isCheck: true },
    {
      key: 'operate',
      colWidth: '120',
      title: '操作',
      type: 'operate',
      isCheck: true,
      fixed:'right',
      buttons: [
        {
          // icon: Document,
          name: '申请协议',
          command: 'handleShowContract',
          isShow: (row) => {
            return row.downloadUrl
          },
        },
        {
          name: '支付',
          command: 'handlePayOpen',
          isShow: (row) => {
            return row.invoiceStatus == 15 && row.payStatus == 5; // invoiceStatus-15 已开 ； payStatus-5 未付
          },
        },
        {
          name: '提完',
          command: 'endPacking',
          isShow: (row) => {
            return row.status == 15;
          },
        },
        {
          name: '删除',
          command: 'deleteItem',
          isShow: (row) => {
            return row.status == 35   // refundStatus 5-待确认 10-已确认 15-待退款 20-已退款。
          },
        },

      ],
    },
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 分页总数
    loading: false
  }
});


const typeList = ref(
  [
    { id: 0, name: '全部',num:0},
    { id: 2, name: '待确认',num:0},
    { id: 3, name: '待签署',num:0},
    { id: 5, name: '待开提箱单' ,num:0},
    { id: 10, name: '待提',num:0},
    // { id: 10, name: '待提未付' },
    // { id: 13, name: '待提已付' },
    { id: 15, name: '已提',num:0},
    // { id: 15, name: '已提未付' },
    // { id: 18, name: '已提已付' },
    { id: 20, name: '未还',num:0 },
    // { id: 20, name: '待还未付' },
    // { id: 25, name: '待还已付' },
    { id: 25, name: '已还' ,num:0},
    // { id: 28, name: '已还未付' },
    { id: 30, name: '已完成',num:0 },
    { id: 40, name: '待取消' ,num:0},
    { id: 35, name: '已取消' ,num:0},
  ]
)


function handleTypeChange(val: any) {
  if(val == 15 || val == 18){
    param.isShowTW = true
  }else{
    param.isShowTW = false
  }
  // param.statusType = val
  param.status = val
  getTableData()
  deselectAll()
}

// 查询各状态数量
async function getAgentStatusCount(){
  let reqParam = {
    containerNo:param.containerNo,
    containerNos:param.containerNos,
    orderNo: param.orderNo,
    carryCityId: param.boxStartCity,
    returnCityId: param.boxBackCity,
    beginCreateTime:'',
    endCreateTime:'',
    beginPlanPickupDate:'',
    endPlanPickupDate:'',
    companyName: param.companyName,
    invoiceStatus: param.invoiceStatus,
    payStatus: param.payStatus,
    businessNo: param.businessNo,
    agentOperatorUserName: param.agentOperatorUserName,
  }
  if (param.createDate) { //下单日期
    reqParam.beginCreateTime = param.createDate[0]
    reqParam.endCreateTime = param.createDate[1]
  }
  if (param.planPickupDate) { //预计提箱日期
    reqParam.beginPlanPickupDate = param.planPickupDate[0]
    reqParam.endPlanPickupDate = param.planPickupDate[1]
  }
  await agentStatusCount(reqParam).then(res => { 
    if(res.code == '00000'){
      typeList.value.forEach(item => { 
        item.num = 0
        res.data.forEach(item1 => { 
          if(item.id == 0){ //全部
            item.num += item1.totalQty
          }else if(item.id == 2 && item1.status ==2){ //待确认
              item.num += item1.totalQty
          }else if(item.id == 3 && item1.status == 3){ //待审核
              item.num += item1.totalQty
          }else if(item.id == 5 && item1.status == 5){ //待开提箱单
              item.num += item1.totalQty
          }else if(item.id == 10 && item1.status == 10 ){ //待提
              item.num += item1.totalQty
          }else if(item.id == 15 && item1.status == 15){ //已提
              item.num += item1.totalQty
          }else if(item.id == 20 && item1.status == 20){ //待还
              item.num += item1.totalQty
          }else if(item.id == 25 && item1.status == 25){ //已还
              item.num += item1.totalQty
          }else if(item.id == 30 && item1.status == 30){ //已完成
              item.num += item1.totalQty
          }else if(item.id == 40 && item1.status == 40){ //待取消
              item.num += item1.totalQty
          }else if(item.id == 35 && item1.status == 35){ //已取消
              item.num += item1.totalQty
          }
       
        });
      });
    
    }
  })
}
//提箱完成
const handlePickupBox = () => {
  let checkAllItem = []
  if(isSelectAll.value){
    checkAllItem = tableRef.value.multipleSelection
  }else{
    checkAllItem = allId.value
  }
  const select = checkAllItem
  let data = []
  select.forEach(item => {
    data.push(item.id)
  });
  // carryFinish
  carryFinish(data).then(res => {
    if(res.code == "00000"){
      getTableData()
    }else{
      console.log("ERROR:",res.msg)
    }
  },error => {
    console.log("ERROR:",error)
  })
}
function getTableData() {
  const { container, containerList } = formatContainerNo(param.containerNo);
  let data = {
    containerNo: container, // 单箱号查询
    containerNos: containerList, // 多箱号查询
    pageNum: param.pageNum,
    pageSize: param.pageSize,
    orderNo: param.orderNo,
    carryCityId: param.boxStartCity,
    returnCityId: param.boxBackCity,
    status: param.status,
    companyName: param.companyName,
    invoiceStatus: param.invoiceStatus,
    businessNo: param.businessNo,
    agentOperatorUserName: param.agentOperatorUserName,
    payStatus: param.payStatus
  }
  if (param.createDate) {
    data.beginCreateTime = param.createDate[0]
    data.endCreateTime = param.createDate[1]
  }
  if (param.planPickupDate) {
    data.beginPlanPickupDate = param.planPickupDate[0]
    data.endPlanPickupDate = param.planPickupDate[1]
  }
  table.config.loading = true;
  // 获取列表数据
  getTable(data).then(res => {
    let list = res.data.list
    setOrderTypeAndRefundStatus(list)
    table.data = res.data.list;
    table.config.total = res.data.total;
  });
  getAgentStatusCount()
  table.config.loading = false;
}
function setOrderTypeAndRefundStatus(list: any) {
  list.forEach((item: any) => {
    let orderType = item.orderType == 15 ? '外调' : ''
    let refundStatus = item.refundStatus ? param.refundStatusFilter[item.refundStatus] : ''
    item.orderTypeAndRefundStatus = orderType + '  ' + refundStatus
  })
}
//重置
function handleReSet() {
  param.containerNo =''
  param.containerNos = []
  param.orderNo = null
  param.boxStartCity = null
  param.boxBackCity = null
  param.createDate = null
  param.planPickupDate = null
  param.invoiceNo = null
  param.companyName = null
  param.invoiceStatus = null
  param.businessNo = null
  param.agentOperatorUserName = null
  param.payStatus = null
  getTableData()
}

//导出
const handleExport = () => {
  let checkAllItem = []
  if(isSelectAll.value){
    checkAllItem = tableRef.value.multipleSelection
  }else{
    checkAllItem = allId.value
  }
  const select = checkAllItem.map(item => item.id)
  if(select.length){
    exportAgentRentOrder(select).then((res) => {
      downloadFile(res, '租箱订单信息')
    })
  }else{
    ElMessage.warning('请检查勾选订单')
  }
  
}

//校验同一公司
const checkCompany = (select: any, msg: string) => {
  let isOnlyOne = true
  let arry = select.map(item => item.companyId)
  arry = [...new Set(arry)]
  if (arry.length > 1) {
    let str = ''
    arry.forEach(companyId => {
      let companyName = select.find(item => item.companyId == companyId).companyName
      if (companyName) {
        str = companyName + ',' + str
      }
    })
    ElMessage.warning('您选择了' + str + arry.length + '家集装箱公司企业的订单,请您重新选择后再' + msg + '。')
    isOnlyOne = false
  }
  return isOnlyOne
}

//申请退款
const tableRef = ref({ multipleSelection: [] })
const handleApplyRefund = () => {
  let checkAllItem = []
  if(isSelectAll.value){
    checkAllItem = tableRef.value.multipleSelection
  }else{
    checkAllItem = allId.value
  }

  const select = checkAllItem
  if (select.length == 0) {
    ElMessage.warning('请选择订单')
    return
  }
  // 校验同一公司
  if (!checkCompany(select, '申请退款')) {
    return
  }
  //校验 未付状态
  const list = select.filter((item) => item.payStatus == '5').map((item) => item.orderNo)
  if (list.length > 0) {
    return ElMessage.warning('您选择的订单号 ' + [...list] + ' 未付租箱款，请您重新选择后再申请退款！')
  }

  param.dialogVisibleRefund = true
}
//申请发票 
const handleApplyInvoiceOpen = () => {
  let checkAllItem = []
  if(isSelectAll.value){
    checkAllItem = tableRef.value.multipleSelection
  }else{
    checkAllItem = allId.value
  }
  const select = checkAllItem
  if (select.length == 0) {
    ElMessage.warning('请选择订单')
    return
  }

  // 校验同一公司
  if (!checkCompany(select, '申请发票')) {
    return
  }
  //校验 已提
  const list_yiTi = select.filter((item) => item.status == '15').map((item) => item.orderNo)
  if (list_yiTi.length > 0) {
    return ElMessage.warning('您选择的订单号 ' + [...list_yiTi] + ' 在提箱中，请您重新选择后再申请发票！')
  }
  //校验 非申请状态
  const list = select.filter((item) => item.invoiceStatus != '5').map((item) => item.orderNo)
  if (list.length > 0) {
    return ElMessage.warning('您选择的订单号 ' + [...list] + ' 发票状态为待开票/已开票，请您重新选择后再申请发票！')
  }
  param.tableData = select
  param.drawer = true
}

//提完
const endPacking = (row: any) => {
  ElMessageBox.confirm('确定已提完？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    let data = []
    data.push(row.id)
    carryFinish(data).then(res => {
      if(res.code == "00000"){
        getTableData()
      }else{
        console.log("ERROR:",res.msg)
      }
    },error => {
      console.log("ERROR:",error)
    })

    // finishPacking(row.packingId).then((res: any) => {
    //   getTableData()
    // })
  }).catch(() => { });
}

// 单个删除 
const deleteItem = (row:any) =>{
  ElMessageBox.confirm('确定要删除订单么？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    rentOrders([row.id]).then((res: any) => { 
      if(res.code == '00000'){
        ElMessage.success('删除成功！')
        getTableData()
      }else{
        ElMessage.warning(res.msg)
      }
    })
  }).catch(() => { });
}

// 批量删除
const batchDelete = () => { 
  let checkAllItem = []
  if(isSelectAll.value){
    checkAllItem = tableRef.value.multipleSelection
  }else{
    checkAllItem = allId.value
  }
  const selectId = checkAllItem.map(item => item.id)
  if(!selectId.length) return ElMessage.warning('请选择要删除的订单！')
    ElMessageBox.confirm('确定要删除订单么？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      rentOrders(selectId).then((res: any) => { 
        if(res.code == '00000'){
          ElMessage.success('删除成功！')
          getTableData()
        }else{
          ElMessage.warning(res.msg)
        }
      })
    }).catch(() => { });
  }
//支付
const rowData = ref()
const handlePayOpen = (row: any) => {
  rowData.value = row
  param.dialogVisible = true
}
const handlePay = () => {
  const data = {
    "id": rowData.value.invoiceId,
    "paymentMethod": rowData.value.paymentMethod,
    "payDate": rowData.value.payDate,
    "payUrl": "[{\"name\":\"20240612/cddd81a833c64a7eab1da5c0aef8dfaf.docx\",\"returnReceiptFileName\":\"国际贸易供应链数字平台电子回执单.docx\",\"url\":\"http://47.122.3.254:9000/default/20240612/cddd81a833c64a7eab1da5c0aef8dfaf.docx\"}]"
  }
  payBoxLabelInvoice(data).then(res => {
    param.newStep = 25
    param.dialogVisible = false
    console.log('pay!')
  })
}


//查看协议
const handleShowContract = (row: any) => {
  param.dialogContract = true
  const downloadUrl = JSON.parse(row.downloadUrl)
  param.contractUrl = downloadUrl.url
}

//
const requestInvoiceSuccess = () => {
  param.drawer = false
  getTableData();
}

//分页
function onTablePageChange(page: any) {
  param.pageNum = page.pageNum;
  param.pageSize = page.pageSize;
  getTableData();
};

//
const showInfo = (row: any) => {
  // router.push('orderInfoRent')
  router.push({
    path:'/placingOrder/exportOrder/details',
    query:{
      orderId:row.id,
      sourceType: 'view',
      businessRoleEnum: 5 
    }
  })
  orderInfo().setRowData(row)
}


// 城市id回写
const startCityId = (id: string) => {
  param.boxStartCity = id
}
const backCityId = (id: string) => {
  param.boxBackCity = id
}

//过滤
const boxTypeFilter = (val: any) => {
  let result = ''
  const boxConditionList = [{ value: 5, label: '40HQ' }, { value: 10, label: '40GP' }, { value: 15, label: '20HQ' }, { value: 20, label: '20GP' }]
  boxConditionList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}

//
const handleClose = () => {
}
const route = useRoute();

onActivated(() => {
   if(route.query.refNo){
    param.orderNo=route.query.refNo
  }
  getTableData()
})

const isSelectAll = ref(true) // true:显示全选按钮  false：显示取消全选按钮
const allId = ref([]) // 使用全选功能时使用
const disableHeaderCheckbox = ref(false) // true:禁用表头全选/全取消 选择框 false:开启 表头全选/全取消 选择框
const isAllCheck = ref(false) //是否使用全选功能
const checkAll = ref([]) //点击全选按钮时 选中列表所有内容（包含当前页和所有后续页）
const slectAll = async(val:any) =>{
    checkAll.value = []
    let data = {
      pageNum:1,
      pageSize:10000,
      statusType: param.statusType || null
    }
    await getTable(data).then(res =>{ 
      if(res.code == "00000" && res.data.list  && res.data.total){
        isSelectAll.value = false
        disableHeaderCheckbox.value = true
        res.data.list.forEach(item => {
          checkAll.value.push(item)
        })
        isAllCheck.value = true
        allId.value = checkAll.value
        tableRef.value.checkAll()
      }else{
        ElMessage.error("全选失败，请刷新页面，或者手动选择")
      }
 })
}

const deselectAll = () =>{
  allId.value = []
  disableHeaderCheckbox.value = false
  tableRef.value.clearCheckAll()
  isSelectAll.value = true
}

const updateSelectAll = (val) => {
  allId.value = val
  // console.log("11111",allId.value)
}


</script>

<style scoped lang='scss'>
  // 为折叠面板图标添加样式
  :deep(.el-collapse-item__header) {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .icon-ele {
    flex-shrink: 0;
    padding-right: 15px;
  }
</style>